<?php

/**
 * MallaCurricular form.
 *
 * @package    sistema_estadisticas
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class MallaCurricularForm extends BaseMallaCurricularForm
{

	public function configure()
	{
		$holder = new sfForm();

		if (!$this->isNew())
		{
			$index = 0;
			$modulos = $this->getObject()->getModulo();
			foreach($modulos as $modulo)
				$this->embedModuloForm($holder, $index++, $modulo);
		}

		$this->embedForm('modulos', $holder);

		$this->widgetSchema['carrera_id']->setOption('order_by', array('denominacion', 'ASC'));
		$this->widgetSchema['f_inicio'] = new WidgetFormDatePick();
	}

	public function addModuloForm($index)
	{
		$holder = $this->getEmbeddedForm('modulos');
		$this->embedModuloForm($holder, $index);
		$this->embedForm('modulos', $holder);

		return $this['modulos']['modulo_' . $index];
	}

	public function bind(array $taintedValues = null, array $taintedFiles = null)
	{
		$holder = $this->getEmbeddedForm('modulos');

		//módulos eliminados
		foreach ($holder as $key => $form)
		{
			if (!isset($taintedValues['modulos'][$key]))
			{
				$holder->widgetSchema->offsetUnset($key);
				$holder->validatorSchema[$key] = new sfValidatorPass();
			}
		}

		//módulos agregados
		if (isset($taintedValues['modulos']))
		{
			foreach ($taintedValues['modulos'] as $key => $values)
			{
				$index = substr($key, 7);
				if (!isset($holder[$key]))
					$this->embedModuloForm($holder, $index);
			}
		}

		$this->embedForm('modulos', $holder);
		parent::bind($taintedValues, $taintedFiles);
	}

	protected function doSave($con = null)
	{
		$this->updateObject();
		$this->getObject()->save($con);

		foreach ($this->getEmbeddedForms() as $holder)
		{
			foreach ($holder->getEmbeddedForms() as $key => $form)
			{
				if ($form->getObject()->isNew())
					$form->getObject()->setMallaId($this->getObject()->getId());
				else
				{
					if (!isset($this->taintedValues['modulos'][$key]))
					{
						$holder->offsetUnset($key);
						$form->getObject()->delete($con);
					}
				}
				
			}
		}

		$this->saveEmbeddedForms($con);

		//malla vigente
		if ($this->getObject()->vigente)
		{
			$table = MallaCurricularTable::getInstance();
			$table->setConnection($con);
			$table->actualizaMallaVigente($this->getObject()->getId(), $this->getObject()->getCarreraId());
		}
	}
	
	private function embedModuloForm($holder, $index, $modulo = null)
	{
		$form = new ModuloForm($modulo);

		$form->widgetSchema['malla_id'] = new sfWidgetFormInputHidden();
		$form->validatorSchema['malla_id'] = new sfValidatorPass();
		$holder->embedForm('modulo_' . $index, $form);
	}

}
